package com.to8to.kitt.utils;

import java.lang.management.ManagementFactory;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;

import org.apache.thrift.TBase;
import org.apache.thrift.protocol.TMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Objects;
import com.to8to.kitt.ThriftMessage;
import com.to8to.kitt.esb.BusMessage;

public class NettyUtils {

	public static Logger logger = LoggerFactory.getLogger(NettyUtils.class);  
	
	public static boolean EXIT_IF_OUT_OF_MEM = true;
	
	public static void sendMsg(ChannelHandlerContext ctx, int seqid, byte type, String name, TBase<?, ?> body)
    {
    	TMessage head = new TMessage();
		
		head.seqid = seqid;
		
		head.type = type;
		
		head.name = name;
		
		ThriftMessage msg = new ThriftMessage(head, body);

		ctx.writeAndFlush(msg);
    }
	   
	public static int hash(ChannelHandlerContext ctx, Object msg)
    {
    	return Objects.hashCode(ctx.channel().remoteAddress().toString(), msg.toString(), System.currentTimeMillis()) + UniqueIdGenerator.uniqueInt();
    }
	
	public static int hash(ChannelHandlerContext ctx, ThriftMessage msg)
    {
    	return Objects.hashCode(ctx.channel().remoteAddress().toString(), msg.getHead().toString(), System.currentTimeMillis() ) + UniqueIdGenerator.uniqueInt();
    }
	
	public static int hash(ChannelHandlerContext ctx, BusMessage msg)
    {
    	return Objects.hashCode(ctx.channel().remoteAddress().toString(), msg.getHead().toString()) + UniqueIdGenerator.uniqueInt();
    }
	
	public static int hash(ChannelHandlerContext ctx, String name)
    {
    	return Objects.hashCode(ctx.channel().remoteAddress().toString(), name) + UniqueIdGenerator.uniqueInt();
    }
	
	public static void exitIfOutOfMemory(Throwable e)
	{
		if(e instanceof OutOfMemoryError)
		{
			System.err.println("OutOfMemoryError!!!!!! EXIT_IF_OUT_OF_MEM: " + EXIT_IF_OUT_OF_MEM);
			
			if(EXIT_IF_OUT_OF_MEM)
			{
				System.err.println("强制退出!!!!");
				System.exit(-1);
			}
			else
			{
				System.err.println("忽略!!!!");
			}
		}
	}
	
	public static boolean checkChannelHealth(Channel channel)
	{
		boolean isOpen = channel.isOpen();
		
		boolean isActive = channel.isActive();
		
		boolean isRegistered = channel.isRegistered();
		
//		boolean isWritable = channel.isWritable();
		
		return isOpen && isActive && isRegistered;// && isWritable;
	}
	
	public static String getPID()
	{
		String name = ManagementFactory.getRuntimeMXBean().getName();  
//		System.out.println(name);  
//		// get pid  
		String pid = name.split("@")[0];  
		return pid;
	}
	

}
